package com.example.musicplayer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.musicplayer.model.Music;

import java.util.ArrayList;

public class MusiclistAdapter extends ArrayAdapter<Music> {
    Context context;
    int resource;
    ArrayList<Music> list;

    public MusiclistAdapter(@NonNull Context context, int resource, ArrayList<Music> list) {
        super(context, resource, list);
        this.context = context;
        this.resource = resource;
        this.list = list;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        Music musicItem = list.get(position);
        String musicName = musicItem.getMusicName();
        String singerName = musicItem.getSingerName();
        if (convertView == null) {
//            LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = LayoutInflater.from(context).inflate(resource, parent, false);

            holder = new ViewHolder();
            holder.musicNameText = convertView.findViewById(R.id.music_name);
            holder.singerNameText = convertView.findViewById(R.id.music_singer);
            // 将holder存入当前item的view
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.musicNameText.setText(musicName);
        holder.singerNameText.setText(singerName);
        return convertView;
    }

    // 定义 ViewHolder 类减少findbyid的次数c
    private static class ViewHolder {
        TextView musicNameText;
        TextView singerNameText;
    }
}
